<template>
    <div class="transfer-management-page">
        <!-- 頁面標題 -->
        <page-title :title="'人事調動管理'" />

        <!-- Tab 切換 -->
        <div class="tab-section">
            <el-tabs v-model="activeTab" @tab-click="handleTabChange">
                <el-tab-pane label="待調動" name="pending"></el-tab-pane>
                <el-tab-pane label="已調動" name="completed"></el-tab-pane>
                <el-tab-pane label="已放棄" name="abandoned"></el-tab-pane>
            </el-tabs>
        </div>

        <!-- 篩選條件區域 -->
        <div class="filter-section">
            <el-form :model="filterForm" label-width="100px" label-position="right">
                <el-row :gutter="20">
                    <el-col :span="4">
                        <el-form-item label="部門">
                            <el-select v-model="filterForm.department" placeholder="請選擇部門" clearable>
                                <el-option v-for="item in departmentOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="職位">
                            <el-select v-model="filterForm.position" placeholder="請選擇職位" clearable>
                                <el-option v-for="item in positionOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="調動類型">
                            <el-select v-model="filterForm.transferType" placeholder="請選擇類型" clearable>
                                <el-option v-for="item in transferTypeOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="員工類型">
                            <el-select v-model="filterForm.employeeType" placeholder="請選擇類型" clearable>
                                <el-option v-for="item in employeeTypeOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="生效日期">
                            <el-date-picker v-model="filterForm.effectiveDateRange" type="daterange" range-separator="至"
                                start-placeholder="開始日期" end-placeholder="結束日期" value-format="YYYY-MM-DD" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="關鍵字搜索">
                            <el-input v-model="filterForm.keyword" placeholder="請輸入員工姓名/手機號碼/編號" clearable
                                @clear="handleSearch" @keyup.enter="handleSearch">
                                <template #append>
                                    <el-button type="primary" @click="handleSearch">
                                        <el-icon>
                                            <Search />
                                        </el-icon>
                                    </el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <!-- 操作按鈕區域 -->
        <div class="action-section">
            <template v-if="activeTab === 'pending'">
                <el-button type="primary" @click="processTransfer">
                    <el-icon>
                        <Edit />
                    </el-icon>
                    <span>辦理調動</span>
                </el-button>
                <el-button type="success" @click="importTransfers">
                    <el-icon>
                        <Upload />
                    </el-icon>
                    <span>導入</span>
                </el-button>
                <el-button type="warning" @click="exportTransfers">
                    <el-icon>
                        <Download />
                    </el-icon>
                    <span>導出</span>
                </el-button>
                <el-button type="info" @click="showMoreActions">
                    <el-icon>
                        <More />
                    </el-icon>
                    <span>更多操作</span>
                </el-button>
            </template>

            <template v-else-if="activeTab === 'completed'">
                <el-button type="warning" @click="exportTransfers">
                    <el-icon>
                        <Download />
                    </el-icon>
                    <span>導出</span>
                </el-button>
            </template>

            <template v-else-if="activeTab === 'abandoned'">
                <el-button type="warning" @click="exportTransfers">
                    <el-icon>
                        <Download />
                    </el-icon>
                    <span>導出</span>
                </el-button>
                <el-button type="danger" @click="batchDelete" :disabled="selectedRecords.length === 0">
                    <el-icon>
                        <Delete />
                    </el-icon>
                    <span>批量刪除</span>
                </el-button>
            </template>
        </div>

        <!-- 表格區域 -->
        <div class="table-section">
            <!-- 待調動表格 -->
            <el-table v-if="activeTab === 'pending'" :data="pendingList" style="width: 100%" v-loading="loading"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="name" label="員工姓名" width="120" />
                <el-table-column prop="originalDepartment" label="原組織部門" width="150" />
                <el-table-column prop="newDepartment" label="調動後組織部門" width="150" />
                <el-table-column prop="transferType" label="調動類型" width="120" />
                <el-table-column prop="onboardingDate" label="入職日期" width="120" />
                <el-table-column prop="applyDate" label="申請日期" width="120" />
                <el-table-column prop="approvalStatus" label="審批狀態" width="120">
                    <template #default="{ row }">
                        <el-tag :type="getApprovalTagType(row.approvalStatus)">
                            {{ row.approvalStatus }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="120" fixed="right">
                    <template #default="{ row }">
                        <el-button type="danger" size="small" @click="abandonTransfer(row)">
                            放棄調動
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 已調動表格 -->
            <el-table v-else-if="activeTab === 'completed'" :data="completedList" style="width: 100%"
                v-loading="loading" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="name" label="員工姓名" width="120" />
                <el-table-column prop="originalDepartment" label="原組織部門" width="150" />
                <el-table-column prop="newDepartment" label="調動後組織部門" width="150" />
                <el-table-column prop="transferType" label="調動類型" width="120" />
                <el-table-column prop="onboardingDate" label="入職日期" width="120" />
                <el-table-column prop="effectiveDate" label="生效日期" width="120" />
                <el-table-column prop="approvalStatus" label="審批狀態" width="120">
                    <template #default="{ row }">
                        <el-tag :type="getApprovalTagType(row.approvalStatus)">
                            {{ row.approvalStatus }}
                        </el-tag>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 已放棄表格 -->
            <el-table v-else-if="activeTab === 'abandoned'" :data="abandonedList" style="width: 100%"
                v-loading="loading" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="name" label="員工姓名" width="120" />
                <el-table-column prop="originalDepartment" label="原組織部門" width="150" />
                <el-table-column prop="newDepartment" label="調動後組織部門" width="150" />
                <el-table-column prop="transferType" label="調動類型" width="120" />
                <el-table-column prop="onboardingDate" label="入職日期" width="120" />
                <el-table-column prop="abandonDate" label="放棄日期" width="120" />
                <el-table-column prop="status" label="狀態" width="120">
                    <template #default="{ row }">
                        <el-tag type="info">
                            {{ row.status }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="reason" label="放棄原因" width="150" show-overflow-tooltip />
                <el-table-column label="操作" width="80" fixed="right">
                    <template #default="{ row }">
                        <el-button type="danger" size="small" @click="deleteRecord(row.id)">
                            刪除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分頁 -->
            <div class="pagination-section">
                <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                    :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                    :total="pagination.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </div>

        <!-- 辦理調動對話框 -->
        <el-dialog v-model="transferDialogVisible" :title="'辦理調動'" width="700px">
            <el-form :model="transferForm" label-width="120px" label-position="right">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="員工姓名" required>
                            <el-input v-model="transferForm.name" placeholder="請輸入員工姓名" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="原部門" required>
                            <el-input v-model="transferForm.originalDepartment" placeholder="原部門" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="新部門" required>
                            <el-select v-model="transferForm.newDepartment" placeholder="請選擇新部門" style="width: 100%">
                                <el-option v-for="item in departmentOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="新職位" required>
                            <el-select v-model="transferForm.newPosition" placeholder="請選擇新職位" style="width: 100%">
                                <el-option v-for="item in positionOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="調動類型" required>
                            <el-select v-model="transferForm.transferType" placeholder="請選擇調動類型" style="width: 100%">
                                <el-option v-for="item in transferTypeOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="生效日期" required>
                            <el-date-picker v-model="transferForm.effectiveDate" type="date" placeholder="請選擇日期"
                                style="width: 100%" value-format="YYYY-MM-DD" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="調動原因">
                    <el-input v-model="transferForm.reason" type="textarea" :rows="3" placeholder="請輸入調動原因" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="transferDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitTransfer">確定</el-button>
            </template>
        </el-dialog>

        <!-- 更多操作下拉菜單 -->
        <el-dropdown ref="moreActionsDropdown" trigger="click" :hide-on-click="false">
            <div style="display: none;"></div>
            <template #dropdown>
                <el-dropdown-menu>
                    <el-dropdown-item @click="batchProcessTransfer">批量辦理調動</el-dropdown-item>
                    <el-dropdown-item @click="batchAbandonTransfer">批量放棄調動</el-dropdown-item>
                </el-dropdown-menu>
            </template>
        </el-dropdown>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { Search, Edit, Upload, Download, Delete, More } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// Tab 切換
const activeTab = ref('pending')

// 篩選表單
const filterForm = reactive({
    department: '',
    position: '',
    transferType: '',
    employeeType: '',
    effectiveDateRange: [],
    keyword: ''
})

// 下拉選項
const departmentOptions = [
    { value: 'rd', label: '研發部' },
    { value: 'hr', label: '人事部' },
    { value: 'finance', label: '財務部' },
    { value: 'marketing', label: '市場部' },
    { value: 'sales', label: '銷售部' }
]

const positionOptions = [
    { value: 'frontend', label: '前端開發' },
    { value: 'backend', label: '後端開發' },
    { value: 'designer', label: '設計師' },
    { value: 'product', label: '產品經理' },
    { value: 'hr', label: '人事專員' }
]

const transferTypeOptions = [
    { value: 'promotion', label: '晉升' },
    { value: 'demotion', label: '降職' },
    { value: 'lateral', label: '平調' },
    { value: 'department', label: '部門調動' },
    { value: 'location', label: '地點調動' }
]

const employeeTypeOptions = [
    { value: 'fulltime', label: '全職' },
    { value: 'parttime', label: '兼職' },
    { value: 'intern', label: '實習生' },
    { value: 'contract', label: '合同工' }
]

// 表格數據
const loading = ref(false)
const pendingList = ref([
    {
        id: 1,
        name: '張三',
        originalDepartment: '研發部',
        newDepartment: '市場部',
        transferType: '部門調動',
        onboardingDate: '2022-05-15',
        applyDate: '2023-06-10',
        approvalStatus: '待審批'
    },
    {
        id: 2,
        name: '李四',
        originalDepartment: '人事部',
        newDepartment: '財務部',
        transferType: '平調',
        onboardingDate: '2021-08-20',
        applyDate: '2023-06-12',
        approvalStatus: '審批中'
    }
])

const completedList = ref([
    {
        id: 3,
        name: '王五',
        originalDepartment: '市場部',
        newDepartment: '研發部',
        transferType: '晉升',
        onboardingDate: '2020-03-10',
        effectiveDate: '2023-06-01',
        approvalStatus: '已通過'
    }
])

const abandonedList = ref([
    {
        id: 4,
        name: '趙六',
        originalDepartment: '財務部',
        newDepartment: '人事部',
        transferType: '平調',
        onboardingDate: '2019-11-05',
        abandonDate: '2023-05-28',
        status: '已放棄',
        reason: '員工個人原因'
    }
])

// 分頁
const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 10
})

// 多選
const selectedRecords = ref([])

// 辦理調動對話框
const transferDialogVisible = ref(false)
const transferForm = reactive({
    name: '',
    originalDepartment: '',
    newDepartment: '',
    newPosition: '',
    transferType: '',
    effectiveDate: '',
    reason: ''
})

// 更多操作下拉菜單
const moreActionsDropdown = ref(null)

// 方法
const handleTabChange = () => {
    selectedRecords.value = []
    handleSearch()
}

const handleSearch = () => {
    loading.value = true
    // 模擬API請求
    setTimeout(() => {
        loading.value = false
    }, 500)
}

const processTransfer = () => {
    if (selectedRecords.value.length === 0) {
        ElMessage.warning('請至少選擇一條記錄')
        return
    }

    if (selectedRecords.value.length > 1) {
        ElMessage.warning('請選擇單條記錄進行辦理')
        return
    }

    const record = selectedRecords.value[0]
    transferForm.name = record.name
    transferForm.originalDepartment = record.originalDepartment
    transferForm.newDepartment = record.newDepartment || ''
    transferForm.newPosition = ''
    transferForm.transferType = record.transferType || ''
    transferForm.effectiveDate = ''
    transferForm.reason = ''

    transferDialogVisible.value = true
}

const submitTransfer = () => {
    // 驗證表單
    if (!transferForm.newDepartment || !transferForm.newPosition ||
        !transferForm.transferType || !transferForm.effectiveDate) {
        ElMessage.warning('請填寫完整信息')
        return
    }

    // 從待調動列表移除
    pendingList.value = pendingList.value.filter(item => item.id !== selectedRecords.value[0].id)

    // 添加到已調動列表
    const transferredEmployee = {
        ...selectedRecords.value[0],
        newDepartment: transferForm.newDepartment,
        transferType: transferForm.transferType,
        effectiveDate: transferForm.effectiveDate,
        approvalStatus: '已通過'
    }
    completedList.value.unshift(transferredEmployee)

    ElMessage.success('辦理調動成功')
    transferDialogVisible.value = false
    selectedRecords.value = []
}

const abandonTransfer = (record) => {
    ElMessageBox.prompt('請輸入放棄原因', '放棄調動', {
        confirmButtonText: '確定',
        cancelButtonText: '取消',
        inputPlaceholder: '請輸入放棄原因',
        inputValidator: (value) => {
            if (!value) {
                return '放棄原因不能為空'
            }
            return true
        }
    }).then(({ value }) => {
        // 從待調動列表移除
        pendingList.value = pendingList.value.filter(item => item.id !== record.id)

        // 添加到已放棄列表
        const abandonedRecord = {
            ...record,
            abandonDate: new Date().toISOString().split('T')[0],
            status: '已放棄',
            reason: value
        }
        abandonedList.value.unshift(abandonedRecord)

        ElMessage.success('已放棄調動')
    }).catch(() => {
        ElMessage.info('已取消操作')
    })
}

const importTransfers = () => {
    ElMessage.info('導入功能待實現')
}

const exportTransfers = () => {
    ElMessage.info('導出功能待實現')
}

const showMoreActions = () => {
    moreActionsDropdown.value.handleClick()
}

const batchDelete = () => {
    if (selectedRecords.value.length === 0) {
        ElMessage.warning('請至少選擇一條記錄')
        return
    }

    ElMessageBox.confirm(
        `確定要刪除選中的 ${selectedRecords.value.length} 條記錄嗎？`,
        '提示',
        {
            confirmButtonText: '確定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        const ids = selectedRecords.value.map(item => item.id)
        abandonedList.value = abandonedList.value.filter(item => !ids.includes(item.id))
        ElMessage.success('刪除成功')
        selectedRecords.value = []
    }).catch(() => {
        ElMessage.info('已取消刪除')
    })
}

const deleteRecord = (id) => {
    ElMessageBox.confirm(
        '確定要刪除這條記錄嗎？',
        '提示',
        {
            confirmButtonText: '確定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        abandonedList.value = abandonedList.value.filter(item => item.id !== id)
        ElMessage.success('刪除成功')
    }).catch(() => {
        ElMessage.info('已取消刪除')
    })
}

const batchProcessTransfer = () => {
    if (selectedRecords.value.length === 0) {
        ElMessage.warning('請至少選擇一條記錄')
        return
    }

    ElMessageBox.prompt('請輸入生效日期', '批量辦理調動', {
        confirmButtonText: '確定',
        cancelButtonText: '取消',
        inputType: 'date',
        inputValidator: (value) => {
            if (!value) {
                return '請輸入生效日期'
            }
            return true
        }
    }).then(({ value }) => {
        const ids = selectedRecords.value.map(item => item.id)
        const toBeMoved = pendingList.value.filter(item => ids.includes(item.id))

        // 添加到已調動列表
        toBeMoved.forEach(record => {
            const transferredEmployee = {
                ...record,
                effectiveDate: value,
                approvalStatus: '已通過'
            }
            completedList.value.unshift(transferredEmployee)
        })

        // 從待調動列表移除
        pendingList.value = pendingList.value.filter(item => !ids.includes(item.id))

        ElMessage.success(`已成功批量辦理 ${toBeMoved.length} 條調動記錄`)
        selectedRecords.value = []
    }).catch(() => {
        ElMessage.info('已取消批量操作')
    })
}

const batchAbandonTransfer = () => {
    if (selectedRecords.value.length === 0) {
        ElMessage.warning('請至少選擇一條記錄')
        return
    }

    ElMessageBox.prompt('請輸入放棄原因', '批量放棄調動', {
        confirmButtonText: '確定',
        cancelButtonText: '取消',
        inputPlaceholder: '請輸入放棄原因',
        inputValidator: (value) => {
            if (!value) {
                return '放棄原因不能為空'
            }
            return true
        }
    }).then(({ value }) => {
        const ids = selectedRecords.value.map(item => item.id)
        const toBeMoved = pendingList.value.filter(item => ids.includes(item.id))

        // 添加到已放棄列表
        toBeMoved.forEach(record => {
            const abandonedRecord = {
                ...record,
                abandonDate: new Date().toISOString().split('T')[0],
                status: '已放棄',
                reason: value
            }
            abandonedList.value.unshift(abandonedRecord)
        })

        // 從待調動列表移除
        pendingList.value = pendingList.value.filter(item => !ids.includes(item.id))

        ElMessage.success(`已成功批量放棄 ${toBeMoved.length} 條調動記錄`)
        selectedRecords.value = []
    }).catch(() => {
        ElMessage.info('已取消批量操作')
    })
}

const handleSelectionChange = (selection) => {
    selectedRecords.value = selection
}

const handleSizeChange = (val) => {
    pagination.pageSize = val
    handleSearch()
}

const handleCurrentChange = (val) => {
    pagination.currentPage = val
    handleSearch()
}

const getApprovalTagType = (status) => {
    switch (status) {
        case '已通過': return 'success'
        case '審批中': return 'warning'
        case '未通過': return 'danger'
        default: return 'info'
    }
}
</script>

<style lang="less" scoped>
.transfer-management-page {
    padding: 20px;
    background-color: #fff;

    .tab-section {
        margin-bottom: 16px;

        :deep(.el-tabs__header) {
            margin-bottom: 0;
        }
    }

    .filter-section {
        padding: 16px;
        margin-bottom: 16px;
        background-color: #fff;
        border-radius: 4px;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
    }

    .action-section {
        margin-bottom: 16px;
        display: flex;
        gap: 12px;
    }

    .table-section {
        background-color: #fff;
        padding: 16px;
        border-radius: 4px;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);

        .pagination-section {
            margin-top: 16px;
            display: flex;
            justify-content: flex-end;
        }
    }
}
</style>